<template>
  <div>
    <div class="search">
      <div class="icon-div"><span class="iconfont">&#xe613;</span></div>
      <input type="text"
             class="search-input"
             placeholder="请输入城市名（如北京、bj、beijing）"
             v-model="keyword"
             :class="[changeSearch]"
             ref="input">
      <button class="button"
              :class="[changeButton]"
              @click="buttonClear">取消
      </button>
      <div class="cancel"
           :class="[cancelSymbol]"
           @click="xClear">
        <span class="iconfont icon-quxiao"></span></div>
    </div>
    <div
      class="search-content"
      v-show="this.list.length"
      ref="contentWrapper">
      <ul>
        <li class="search-first">
          {{this.show}}
        </li>
        <li
          class="search-item"
          v-for="item of this.list"
          :key="item.id"
          @click="handleItemClick(item.name)"
        >{{item.name}}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  import BScroll from 'better-scroll'
  import {disreslove} from '../../../utils/utils.js'

  export default {
    name: "locationHeader",
    props: {
      cities: Object
    },
    methods: {
      handleItemClick(city) {
        this.$store.dispatch('change', city);
        this.$router.push('/');
      },
      buttonClear() {
        this.keyword = ' ';
        this.flag = "2";
      },
      xClear() {
        this.keyword = ' ';
        this.flag = "33";
        const elementInput = this.$refs.input;
        elementInput.focus();
      },
      addClass() {
        this.changeSearch = "changeSearch";
        this.changeButton = "changeButton";
        this.cancelSymbol = "cancelSymbol";
      },
      removeClass() {
        this.changeSearch = "";
        this.changeButton = "";
        this.cancelSymbol = "";
      },
      removeBack() {
        this.list = [];
        this.show = '';
        this.removeClass();
      },
      showError(content) {
        this.list = [''];
        this.show = "搜索无结果" + this.keyword;
      },
      loopAlphabet(lowerContent) {
        // const citiesWrapper = this.cities;
        for (let i in this.cities) {
          if (i.toLowerCase()
            .indexOf(lowerContent.substr(0, 1)) > -1) {
            let arr = [];
            this.cities[i].forEach((value) => {
              //
              arr.push(value.spell.substr(lowerContent.length - 1, 1));
              let a = [...new Set(arr)];//ES6去重方法
              this.iLetter = a.toString();
            })
          }
        }
      },
      searchAlph(content) {
        let result = [];
        const lowerContent = content.toLowerCase();//转换为小写字母

        for (let i in this.cities) {
          let haveAlph = i.toLowerCase()//过滤出输入首字母所在的城市
            .indexOf(lowerContent.substr(0, 1)) > -1;
          // console.log(haveAlph + "ffffffffff");
          if (haveAlph) {
            // console.log("-1--");
            this.cities[i].forEach((value) => {
              // console.log("0--");
              //输入的字母包含在城市拼音字母
              if (value.spell.indexOf(lowerContent) > -1) {
                // console.log("1--");
                result.push(value);//存进数组
                this.list = result;
                this.show = "请输入城市名（如北京、bj、beijing）";
                //输入的字母没有包含在城市拼音字母
              } else if (lowerContent.indexOf(value.spell) > -1) {
                console.log("2--");
                this.show = "搜索无结果" + this.keyword;
              } else {
                // console.log("3--");
                this.loopAlphabet(lowerContent);
                //console.log(this.iLetter);
                if (!(this.iLetter.indexOf(
                  lowerContent.substr(lowerContent.length - 1, 1)) > -1)) {
                  // console.log("4--");
                  this.show = "搜索无结果" + this.keyword;
                  this.iLetter = '';
                }
              }
            })
          } else if (//没有首字母uivo的城市
            lowerContent.substr(0, 1) === 'u'
            || lowerContent.substr(0, 1) === 'i'
            || lowerContent.substr(0, 1) === 'v'
            || lowerContent.substr(0, 1) === 'o') {
            this.show = "搜索无结果" + this.keyword;
            this.list = [''];
          }
        }
      },
      loopWord(content) {
        const citiesWrapper = this.cities;//异步加载的数据 先保存
        for (let i in citiesWrapper) {
          if (i.toLowerCase()
            .indexOf(disreslove(content).substr(0, 1)
              .substr(0, 1)) > -1) {
            let arr = [];
            citiesWrapper[i].forEach((value) => {
              arr.push(value.name.substr(content.length - 1, 1));
              let a = [...new Set(arr)];//ES6去重方法
              this.iWord = a.toString();
            })
          }
        }
      },
      searchWord(content) {
        let result = [];
        for (let i in this.cities) {
          let haveAlph = i.toLowerCase()
            .indexOf(
              disreslove(content.substr(0, 1))
                .substr(0, 1)) > -1;
          if (haveAlph) {
            this.cities[i].forEach((value) => {
              if (value.name.indexOf(content) > -1) {
                this.show = "请输入城市名（如北京、bj、beijing）";
                result.push(value);
                this.list = result;
              } else if (content.indexOf(value.name) > -1) {
                console.log("2--");
                this.show = "搜索无结果" + this.keyword;
              } else {
                this.loopWord(content);
                if (!(this.iWord.indexOf(
                  content.substr(content.length - 1, 1)) > -1)) {
                  this.show = "搜索无结果" + this.keyword;
                  this.iWord = '';
                }
              }
            })
          }
        }
      }
    }
    ,
    data() {
      return {
        keyword: '',
        changeSearch: '',
        changeButton: '',
        cancelSymbol: '',
        show: '请输入城市名（如北京、bj、beijing）',
        list: [
          // {
          //   id: '0000000001',
          //   name: '北京'
          // },
          // {
          //   id: '0000000002',
          //   name: '北京'
          // },
          // {
          //   id: '0000000003',
          //   name: '北京'
          // },
          // {
          //   id: '0000000004',
          //   name: '北京'
          // },
          // {
          //   id: '0000000005',
          //   name: '北京'
          // },
          // {
          //   id: '0000000006',
          //   name: '北京'
          // },
          // {
          //   id: '0000000007',
          //   name: '北京'
          // },
          // {
          //   id: '0000000008',
          //   name: '北京'
          // },
          // {
          //   id: '0000000009',
          //   name: '北京'
          // },
          // {
          //   id: '0000000010',
          //   name: '北京'
          // },
          // {
          //   id: '0000000011',
          //   name: '北京'
          // },
          // {
          //   id: '0000000012',
          //   name: '北京'
          // },
          // {
          //   id: '0000000013',
          //   name: '北京'
          // },
          // {
          //   id: '0000000014',
          //   name: '北京'
          // },
          // {
          //   id: '0000000015',
          //   name: '北京'
          // },
          // {
          //   id: '0000000016',
          //   name: '北京'
          // },
          // {
          //   id: '0000000017',
          //   name: '北京'
          // },
          // {
          //   id: '0000000018',
          //   name: '北京'
          // }
        ],
        flag: '1',
        iLetter: '',
        iWord: ''
      }
    }
    ,
    watch: {
      keyword() {
        let content = this.keyword.trim();//trim()删除字符串的头尾空格
        this.addClass();
        if (content === '') {
          /**
           * 内容为空
           flag代表内容为空时的区分标志位
           1表示本身没有输入或者逐字清除
           2表示点击清除按钮
           否则表示点击×按钮
           */
          if (this.float === '1') {
            this.removeBack();

          } else if (this.flag === '2') {
            this.keyword = '';
            this.removeBack();

          } else {
            this.keyword = '';

          }
        } else if (/^[0-9]+$/.test(content)) {
          //内容为数字
          this.showError(content);

        } else if (/^[a-zA-Z]+$/.test(content)) {
          //内容为字母
          this.searchAlph(content);

        } else if (/^[\u4e00-\u9fa5]+$/.test(content)) {
          //内容为汉字
          this.searchWord(content);

        } else {
          //其它内容
          this.showError(content);
        }
      }
    }
    ,
    mounted() {
      this.scroll = new BScroll(this.$refs.contentWrapper, {
        click: true,
        mousewheel: {
          speed: 20,
          invert: false,
          easeTime: 300
        }
      })
    }
  }
</script>

<style lang="stylus" scoped>
  .search
    position: relative
    height: .72rem
    background: #e0e4ec
    padding: .2rem

  .icon-div
    position: absolute
    top: .4rem
    left: .4rem
    color: #666

  .search-input
    height: .72rem
    line-height: .72rem
    width: 100%
    text-align: left
    box-sizing: border-box
    padding-left: .6rem
    border-radius: .06rem
    color: #666

  .changeSearch
    width: 88%
    margin-right: .1rem

  .button
    display: none

  .changeButton
    display: block
    color: #888
    font-weight: bold
    position: absolute
    top: .29rem !important
    right: .22rem !important
    z-index: 100000
    font-size: .33rem
    text-align: center
    background: none

  .cancel
    display: none

  .cancelSymbol
    display: block
    position: absolute
    top: 50%
    right: 15%
    color: #fff
    z-index: 101
    background: #ccc
    padding: 0.05rem
    border-radius: 50%
    text-align: center
    transform: translate(-50%, -50%)

  .search-content
    overflow: hidden
    position: absolute
    z-index: 101
    top: 1.1rem
    left: 0
    right: 0
    bottom: 0
    background: #eee

  .search-first
    line-height: .22rem
    padding: .2rem
    padding-left: .4rem
    margin-bottom: .06rem
    background: #fff
    font-size: .1rem
    color: #aaa

  .search-item
    line-height: .82rem
    padding-left: .2rem
    margin-bottom: .06rem
    color: #666
    background: #fff

</style>
